package control;

import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.service.MemberService;
import model.vo.MemberVO;

import org.json.simple.JSONObject;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;


public class MemberController extends MultiActionController{
	private String actionName="memberAction.do";
	private MemberService memberService;
	public void setMemberService(MemberService memberService) {
		this.memberService = memberService;
	}
	
	//로그아웃
	public ModelAndView logout(HttpServletRequest request,HttpServletResponse response) throws Exception{
		ModelAndView mv=new ModelAndView();
		mv.setViewName("logout");
		return mv;
	}
	
	
	
	//////////---20110810 이하 페이지 전부 필요없음.(로그인은 포탈에서 해서옴)
	
	
	//로그인 (Ajax)
	public void login(HttpServletRequest request,HttpServletResponse response) throws Exception{
		String logId = request.getParameter("logId").toLowerCase();
		String logPw = request.getParameter("logPw").toLowerCase();
		//ajax에서 쓰기 위해 json타입으로 값 저장
		JSONObject obj=new JSONObject();
		try{
			boolean idFlag = memberService.findId(logId);
			// id가 있는지 체크
			if (idFlag) {// id 있으면
				MemberVO mvo = memberService.login(logId, logPw);// 아이디 비번 체크
				boolean flag = false;
				if (mvo != null) {// 참이면 세션 설정
					HttpSession session = request.getSession();
					session.setAttribute("USER_ID", mvo.getLogID());
					session.setAttribute("USER_NAME", mvo.getName());
					
					//session.setAttribute("mvo", mvo);
					//세션 시간 설정(20분)
					session.setMaxInactiveInterval(-1);
					session.removeAttribute("proNm"); 
					session.removeAttribute("proDayIndex"); 
					session.removeAttribute("lastProId"); 
					session.removeAttribute("magamSession"); 
					flag = true;
					//System.out.println(mvo);
				}
				obj.put("flag", flag);
			} else {// id가 없으면
				obj.put("idFlag", "N");
			}
		}catch(Exception e){
			obj.put("idFlag", "Y");
			System.out.println(e.getMessage());
			obj.put("errorMessage", e.getMessage());
			e.printStackTrace();
		}
		PrintWriter out = response.getWriter();
		out.print(obj.toString());
	}
	
	//환경설정 페이지로 이동
	public ModelAndView memberConfig(HttpServletRequest request,HttpServletResponse response) throws Exception{
		ModelAndView mv=new ModelAndView();
		List list=memberService.memberList();
		//리스트라는 객체에 list를 담아 보넴(request.setAttribute와 동일)
		mv.addObject("list",list);
		mv.setViewName("memberConfig_SL");
		return mv;
	}
	//비밀번호 변경 페이지로 이동
	public ModelAndView changePassword(HttpServletRequest request,HttpServletResponse response) throws Exception{
		ModelAndView mv=new ModelAndView();
		//리스트라는 객체에 list를 담아 보넴(request.setAttribute와 동일)
		mv.setViewName("changePassword");
		return mv;
	}
	
	//비밀번호 변경
	public ModelAndView member_changePassword(HttpServletRequest request,HttpServletResponse response) throws Exception{
		String logID = request.getParameter("logID");
		String curpass = request.getParameter("curpass");
		String password = request.getParameter("password");
		HttpSession session = request.getSession(false);
		ModelAndView mv = new ModelAndView();
		if(session!=null && session.getAttribute("USER_ID")!=null){
			MemberVO mvo = (MemberVO) session.getAttribute("mvo");
			System.out.println("초기 : "+mvo);
			String cpass = mvo.getPassword();
			if (cpass.equals(curpass)) {
				memberService.member_updatePassword(logID, password);
				mvo.setPassword(password);
				System.out.println("후기 : "+mvo);
				session.setAttribute("mvo", mvo);
				//세션 시간 설정(20분)
				session.setMaxInactiveInterval(20*60);
				mv.addObject("info", true);
			} else {
				mv.addObject("info", false);
			}
		}
		mv.setViewName("changePassword_result");
		return mv;
	}
	
	//환경설정 등록 페이지
	public ModelAndView member_insertPage(HttpServletRequest request,HttpServletResponse response) throws Exception{
		ModelAndView mv=new ModelAndView();
		//최대 순번 구해오기
		mv.setViewName("memberConfig_SI");
		return mv;
	}
	
	//멤버 등록 유효성 검사(Ajax)
	public void searchMemberId(HttpServletRequest request,HttpServletResponse response) throws Exception{
		//자산코드의 값을 UTF-8로 인코딩하여 받음
		response.setContentType("text/html;charset=UTF-8");
		response.setHeader("Cache-Control", "no-cache");
		String logID= request.getParameter("logID");
		System.out.println(logID);
		JSONObject obj=new JSONObject();
			boolean logIDFlag = memberService.searchMemberId(logID);
			if (logIDFlag) {// id가 있으면
				obj.put("logIDFlag", "N");
				} else {// id가  없으면
				obj.put("logIDFlag", "Y");
			}
		PrintWriter out = response.getWriter();
		out.print(obj.toString());
	}	
	//멤버 등록
	public ModelAndView member_insert(HttpServletRequest request,HttpServletResponse response) throws Exception{
		ModelAndView mv=new ModelAndView();
		MemberVO vo=new MemberVO();
		//vo에 request값들은 담음
		bind(request, vo);
		System.out.println("멤버 request값: "+vo);
		try{
			memberService.member_insert(vo);
			mv.addObject("actionName",actionName);
			mv.addObject("pageName","memberConfig");
			mv.setViewName("insertAndDeleteResult");
		}catch (SQLException e) {//SQL에러시
			System.out.println(e.getMessage());
			mv.setViewName("failResult");
		}
		return mv;
	}
	//멤버  수정 페이지로 이동
	public ModelAndView member_updatePage(HttpServletRequest request,HttpServletResponse response) throws Exception{
		response.setContentType("text/html;charset=UTF-8");
		response.setHeader("Cache-Control", "no-cache");
		ModelAndView mv=new ModelAndView();
		//int asset_no=Integer.parseInt(request.getParameter("asset_no")); //서비스단에서 인트로 바꿔줌 
		MemberVO vo=memberService.member_updatePage(request.getParameter("logID"));
		System.out.println(vo);
		mv.addObject("update","Y");
		mv.addObject("vo",vo);
		mv.setViewName("memberConfig_SI");
		return mv;
	}
	
	//멤버  수정 
	public ModelAndView member_update(HttpServletRequest request,HttpServletResponse response) throws Exception{
		ModelAndView mv=new ModelAndView();
		MemberVO vo=new MemberVO();
		//vo에 request값들은 담음
		bind(request, vo);
		System.out.println("멤버 수정값 request값들: "+vo);
		memberService.member_update(vo);
		mv.addObject("actionName",actionName);
		mv.addObject("pageName","memberConfig");
		mv.setViewName("insertAndDeleteResult");
		return mv;
	}
	
	//멤버  삭제
	public ModelAndView member_delete(HttpServletRequest request,HttpServletResponse response) throws Exception{
		ModelAndView mv=new ModelAndView();
		String logID[]=request.getParameterValues("check");
		//체크 박스로 삭제
		if(logID!=null){
			//체크된 것들의 value값을 받음
			for(int i=0;i<logID.length;i++){
				System.out.println(logID[i]);
				//삭제
				//int asset_no=Integer.parseInt(assetNo[i]); //서비스단에서 인트로 바꿔줌 
				memberService.member_delete(logID[i]);
			}
		}
		//삭제후 list 페이지로 이동
		mv.addObject("actionName",actionName);
		mv.addObject("pageName","memberConfig");
		mv.setViewName("insertAndDeleteResult");
		return mv;
	}
}
